/*
 * Copyright [2013-2021], Alibaba Group Holding Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.polardbx.executor.balancer.solver;

import java.util.HashMap;
import java.util.Map;

public class LpExpression {
    double constant;
    Map<LpVariable, Double> terms;

    double rhs;

    char sense;

    String name;

    final char LQ_SENSE = 'L';

    final char GQ_SENSE = 'G';

    final char EQ_SENSE = 'E';

    public LpExpression() {
        terms = new HashMap<>();
    }

    public LpExpression add(double value) {
        constant += value;
        return this;
    }

    public LpExpression add(double value, LpVariable variable) {
        Double old;
        if ((old = terms.get(variable)) != null) {
            value += old.doubleValue();
        }
        terms.put(variable, value);
        return this;
    }

    public LpExpression add(LpVariable variable) {
        Double old;
        double value = 1.0;
        if ((old = terms.get(variable)) != null) {
            value += old.doubleValue();
        }
        terms.put(variable, value);
        return this;
    }

    public LpExpression geq(double value) {
        rhs = value;
        sense = GQ_SENSE;
        return this;
    }

    public LpExpression leq(double value) {
        rhs = value;
        sense = LQ_SENSE;
        return this;
    }

    public LpExpression eq(double value) {
        rhs = value;
        sense = EQ_SENSE;
        return this;
    }

    public LpExpression name(String name) {
        this.name = name;
        return this;
    }
}
